/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-24 22:18:21
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.risk.repository;

import com.joysuch.wwyt.risk.entity.RiskEvaluationPlan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * RiskEvaluationPlanDao
 */
public interface RiskEvaluationPlanDao extends JpaRepository<RiskEvaluationPlan, Long> {
    public Page<RiskEvaluationPlan> findAll(Specification<RiskEvaluationPlan> spec, Pageable pageable);

    public RiskEvaluationPlan save(RiskEvaluationPlan bean);

    public void delete(RiskEvaluationPlan bean);


    RiskEvaluationPlan findFirstByRiskPointIdOrderByIdDesc(Long id);

    public RiskEvaluationPlan findFirstByRiskPointId(Long id, Sort sort);

    public RiskEvaluationPlan findFirstByRiskDistrictId(Long id, Sort sort);

    /**
     * 查找指定时间范围内的评估计划
     * @param startTime
     *            开始时间
     * @param endTime
     *            结束时间
     * @return 任务列表
     */
    public List<RiskEvaluationPlan> findByNextEvaluationTimeBetween(Date startTime, Date endTime);

    @Query(value = "select rep.* from wwyt_risk_evaluation_plan rep " +
            "inner join " +
            "(select max(id) as id,TENENT_ID,ORG_CODE from wwyt_risk_evaluation_plan where DELETE_FLAG='0' group by RISK_POINT_ID,TENENT_ID,ORG_CODE ) rept " +
            "on rept.id = rep.id " +
            "where rep.DELETE_FLAG='0' " +
            "and rep.RISK_POINT_ID is not null " +
            "and RISK_POINT_ID in (?1)", nativeQuery = true)
    List<RiskEvaluationPlan> findLastPlanByPointIds(Set<Long> pointIds);

    @Query(value = "select count(id) from wwyt_risk_evaluation_plan where risk_point_id = ?1 and DELETE_FLAG = '0'", nativeQuery = true)
    int countByRiskPointId(Long id);

    void deleteByRiskPointId(Long riskPointId);

}
